package com.kepler.social.generic;


import com.kepler.social.common.exception.SystemException;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
// TODO Helper -> Support
public class MailHelper {

    private static final Logger log = LoggerFactory.getLogger(MailHelper.class);

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendSimpleMail(String to, String subject, String text) {
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom(from);//发送者
        smm.setTo(to);//收件人
        smm.setSubject(subject);//邮件主题
        smm.setText(text);//邮件内容
        mailSender.send(smm);//发送邮件
    }

    public void sendHtmlMail(String to, String subject, String content) {
        // 注意这里使用的是MimeMessage
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 发件人
            helper.setFrom(from);
            // 收件人
            helper.setTo(to);
            // 邮件标题
            helper.setSubject(subject);
            // 邮件内容，第二个参数：格式是否为html
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送html邮件失败 {} {} {}", to, subject, content);
            throw new SystemException("发送邮件失败");
        }

    }

}